/**
 * Created by bianlian on 16/9/19.
 */

import React, { Component, PropTypes } from 'react';
import { Image, StyleSheet, View, TouchableOpacity, Alert, Platform, NativeModules, BackAndroid, Switch, Text } from 'react-native';
import { MtContainer, MtSeparator, MtChar, MtColor, MtActionButton, MtToast } from 'martian-ui';
var RNBridgeModule= NativeModules.RNBridgeModule;
import {UpdateDeviceInfo, fetchDeviceDetailById, controlDevice} from '../action/girlAction';
import { bindActionCreators } from 'redux';
import {connect} from 'react-redux';
const EntityLabels = require('../constants/entities');
const MtIcon = require('martian-icon');
const { MtT7, MtLabel, MtL3, MtL1 } = MtChar;
import Dimensions from 'Dimensions';
const width = Dimensions.get('window').width;
const assert = require('assert');
import assign from 'lodash/assign';
import TopLight from '../container/Devices/TopLight';
import BoxShadowYaGuan from '../components/common/BoxShadowYaGuan';
const values = require('lodash/values');
// 一些常量设置
var cols = 2;
var cellWH = (width - 45)/2;
var vMargin = (width - cellWH * cols) / (cols + 1);
var hMargin = 25;
import { modelToKeyString, modelToComponet } from '../utils/modelToKeyString';
var jsonToNomarl = {
  "Switch": "switch",
  "Switch_1": "switch1",
  "Switch_2": "switch2",
  "Switch_3": "switch3",
};

class YaguanRoomDeviceListCell extends Component {

  // 构造
  constructor(props) {
    super(props);
    this.state = {
      value: false,
      disabled: false,
      changeTxt:'切换Switch',
    }

  }

  /**
   * 调用数据 :
   *      1. 当触发Action方法请求数据反馈到Reducer中
   *      2. Reducer通过ActionType判断该更新哪个UI中的State
   *      3. 最后刷新界面显示数据
   */
  componentWillMount() {
    this.convertPropsToStates(this.props);

    if (Platform.OS === 'android') {
      BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
    }
  }

  convertPropsToStates(props) {
    const { devicesEntities, deviceId } = props;
    const device = devicesEntities[deviceId];

    if (device && device.status){
      if (device.status.switch === 'true'){
        this.setState({
          value: true,
        })
      }
      else {
        this.setState({
          value: false,
        })
      }
    }

    const newState = assign({
      device,
    });

    if (newState) {
      this.setState(newState);
    }
  }

  componentWillReceiveProps(nextProps) {
    this.convertPropsToStates((nextProps));
  }



  componentDidMount() {
    const { fetchDeviceDetailById,  deviceId} = this.props;
    fetchDeviceDetailById(deviceId);
    if (Platform.OS === 'android') {
      BackAndroid.addEventListener('hardwareBackPress', () => this.onBackAndroid());
    }
  }



  /**
   * 监听Android返回按键
   * @returns {boolean}
   */
  onBackAndroid() {

    const {navigator} = this.props;
    if (navigator.getCurrentRoutes().length > 1) {
      navigator.pop();
      return true;
    }
    //退出
    return false;

  }
  controlAir(params){
    const {controlDevice, deviceId} = this.props;
    controlDevice(params, deviceId);
  }

  render() {
    const {  roomName, navigator } = this.props;
    const { device } = this.state;
    const { name, model, deviceId, status } = device || {};
    let currentValue;


    if(!model || model === ''){
      assert('model非法')
    }

    const key_string = model && modelToKeyString(model);

    const { value }=  this.state;

    const Button = (
      <View style={styles.buttonContainer}>
        <Switch value={value}
                onTintColor='#00A5AD'
                onValueChange={
                  (value)=>{
                    this.setState({
                      value
                    },()=>{
                      const newAirParams = {'Switch': value}
                      this.controlAir(newAirParams);
                    })
                  }}
        />


      </View>
    );

    return (
      <TouchableOpacity activeOpacity={0.5} onPress={()=>{
        if(modelToComponet(model) && modelToComponet(model) !== '' && model.indexOf("ARGRACE_LIVING_WALLSWITCH")< 0 ){
          navigator.push({
            component: modelToComponet(model),
            params: {
              navigator,
              deviceId

            }
          })
        }

      }}>
        <View style={{marginLeft: 15, marginBottom: 15,}}>
          <BoxShadowYaGuan
            width={cellWH}
            height={cellWH - 43}
            renderItem={()=>{
                return (
                  <View style={styles.innerViewStyle}>
                    <View style={{ flexDirection: 'row'}}>
                      <View style={{ marginLeft: 15, marginTop: 15, marginRight: 10, flex: 1 }}>
                        <Text numberOfLines={1} style={styles.deviceName}>{name}</Text>
                        <Text numberOfLines={1} style={styles.roomName}>{roomName}</Text>
                      </View>
                      <Image source={require('../img/shebei.png')} style={styles.iconStyle}/>
                    </View>
                    {model.indexOf("ARGRACE_LIVING_WALLSWITCH")>=0 &&
                    <View style={{ flexDirection: 'row', marginLeft: 15, marginTop: 15, alignItems: 'center',}}>
                      <Text style={styles.deviceStatus}>{value ? '工作中' : '关闭'}</Text>
                      {Button}
                    </View>

                    }
                  </View>
                )
            }}
          />
        </View>
      </TouchableOpacity>

    );

  }
}


const styles = StyleSheet.create({
  rowContainer: {
    backgroundColor: 'white',
    marginTop: 10,
  },
  tagInner: {
    alignItems: 'flex-end',
    height: 55,
    justifyContent: 'center',
  },
  tagColorBox: {
    height: 26,
    paddingHorizontal: 10,
    justifyContent: 'center',
    alignItems: 'center',
  },
  separator: {
    paddingHorizontal: 15,
  },
  favItem: {
    height: 50,
    paddingHorizontal: 15,
    flexDirection: 'row',
    alignItems: 'center',
  },
  circular: {
    borderRadius: 2,
    height: 26,
    backgroundColor: '#e3f1fe',
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonContainer: {
    flex: 1,
    marginRight: 10,
    alignItems: 'flex-end',
  },

  listViewStyle:{
    // 改变主轴的方向
    flexDirection:'row',
    // 多行显示
    flexWrap:'wrap',
    // 侧轴方向
    alignItems:'center', // 必须设置,否则换行不起作用
  },
  iconStyle:{
    width: 44,
    height: 44,
    marginRight: 15,
    marginTop: 10,
  },
  innerViewStyle:{
    width: cellWH,
    height: cellWH - 43,
    backgroundColor: '#fff',
    borderRadius: 6,
  },
  deviceName: {
    fontSize: 14,
    color: '#333333',
  },
  roomName: {
    fontSize: 13,
    color: '#CCCCCC',
  },
  deviceStatus: {
    fontSize: 12,
    color: '#666666',
  }
});


function mapDispatchToProps(dispatch) {
  const actions = {
    UpdateDeviceInfo,
    fetchDeviceDetailById,
    controlDevice,
  };
  return bindActionCreators(actions, dispatch);
}

function mappingStateToProps(state, ownProps) {
  const entities= state['entities'];
  const devicesEntities = entities[EntityLabels.devices];
  const assessTokenEntity = entities[EntityLabels.token];
  const assessToken = assessTokenEntity && values(assessTokenEntity)[0].assessToken;


  return {
    devicesEntities,
    assessToken
  }
}


module.exports = connect(mappingStateToProps, mapDispatchToProps)(YaguanRoomDeviceListCell);
